import {Button, Form, Input, message} from "antd";
import useTime from "@/hooks/useTime.ts";
import {emailCode, register} from '@/api/login.ts'
import {ETabItemKey} from '@/views/Login/index.tsx'
import styles from "@/views/Login/login.module.scss";
import {useState} from "react";

interface IForm {
    email: string
    code: string
}
interface IProps {
    change: (key: ETabItemKey) => void
}
const Register = ({ change }: IProps) => {
    const [form] = Form.useForm()
    const [email, setEmail] = useState('')
    const { time, changeTime } = useTime()
    const onFinish = async (values: IForm) => {
        const data = { ...values, mode: ETabItemKey.register }
        const response = await register(data)
        if(response.code === 200) {
            message.success('注册成功')
        } else {
            message.error(response.data.msg || '注册失败')
        }
        form.resetFields()
        setEmail('')
        change(ETabItemKey.email)
    }
    const emailChange = (e: { target: { value: string } }) => {
        setEmail(e.target.value)
    }
    const handleEmail = () => {
        if(email) {
            changeTime(60,  async () => {
                await emailCode({ email, mode: ETabItemKey.register })
            })
        } else {
            message.error('请填写邮箱后发送验证码')
        }
    }
    return (
        <>
            <h1 style={{fontWeight: 700, marginBottom: '12px', color: '#FFF'}}>账号注册</h1>
            <div className={styles.info}
                 style={{color: '#A1A1A1', marginBottom: '28px'}}>请输入您的邮箱注册
            </div>
            <Form form={form} onFinish={onFinish}>
                <Form.Item name='email' label={<span style={{color: '#FFF', fontWeight: 'bold'}}>邮&nbsp;&nbsp;&nbsp;箱</span>}
                           rules={[{required: true, message: '请输入邮箱'}]}>
                    <Input onChange={emailChange} suffix={<span style={{ cursor: 'pointer' }} className={ time === 0 ? '' : styles.timeBtn } onClick={handleEmail}>{ time === 0 ? '获取验证码' : `${time}s后可重新获取`}</span>}/>
                </Form.Item>
                <Form.Item name='code' label={<span style={{color: '#FFF', fontWeight: 'bold'}}>验证码</span>}
                           rules={[{required: true, message: '请输入验证码'}]}>
                    <Input maxLength={6}/>
                </Form.Item>
                <Form.Item>
                    <Button style={{width: '100%'}} htmlType="submit" type='primary'>注册</Button>
                </Form.Item>
            </Form>
        </>
    )
}

export default Register